<?php

/**
 * @filename Agent.php
 * @encoding UTF-8
 *
 * @author 徐小军
 *
 * @link http://www.okd100.com
 *
 * @copyright 南昌欧科达科技有效公司
 * @datetime 2016-7-27  14:04:47
 *
 * @version 1.0
 * @Description 代理商管理
 */

namespace app\admin\controller;

use app\common\model\User as UserModel;
use app\common\model\AgentApplication as AgentAppModel;
use app\common\model\LineTicket as LineTicketModel;
use app\common\model\Line as LineModel;
use app\common\model\CashFlow as CashFlowModel;
use app\common\model\Sysconfig as SysconfigModel;

class Agent extends Common
{
    private static $ZWSP = '​';

    /**
     * 申请代理.
     */
    public function applyAgent()
    {
        if (IS_POST) {
            $data = input('post.');
            $usr = UserModel::get(session('user_id'));
            $apps = $usr->agent_applications()->where('application_status', 0)->count();
            if ($usr->user_type != 'user') {
                return error('你已经是代理了！');
            }
            if ($apps > 0) {
                return error('您的申请还在审核中...');
            }
            foreach ($data as $key => &$col) {
                $col = $col == '- 请选择 -' ? '' : $col;
            }
            $usr->agent_applications()->save([
                'location' => $data['province'].self::$ZWSP.$data['city'].self::$ZWSP.$data['area'],
                'comments' => $data['comments'],
            ]);

            return success('申请成功');
        } else {
            $usr = UserModel::get(session('user_id'));
            $time = date('Y-m-d H:i:s');
            $this->assign('user', $usr);
            $this->assign('nowtime', $time);

            return $this->fetch();
        }
    }

    public function setAgent()
    {
        if (IS_POST) {
            $data = input('post.');
            $usr = UserModel::get($data['user_id']);
            $apps = $usr->agent_applications()->where('application_status', 0)->count();
            if ($usr->user_type != 'user') {
                return error('这用户已经是代理了');
            }
            if ($apps > 0) {
                return error('此用户还有未处理的申请');
            }
            foreach ($data as $key => &$col) {
                $col = $col == '- 请选择 -' ? '' : $col;
            }
            $usr->agent_applications()->save([
              'location' => $data['province'].self::$ZWSP.$data['city'].self::$ZWSP.$data['area'],
              'comments' => $data['comments'],
            ]);
            $app = $usr->agent_applications()->where('application_status', 0)->find();
            $app->confirm_user = session('user_id');
            $app->application_status = '已通过';
            $app->save();
            UserModel::get($app->user->user_id)->mails()->save(config('msg.send_agent_ok'));

            return success('成功将此用户变为代理');
        } else {
            return error('非法访问');
        }
    }
    /**
     *  操作通过/未通过申请.
     */
    public function caozuo()
    {
        if (session('user')->user_type == 'user' or session('user')->user_type == 'agent') {
            return error('没有权限');
        }
        $type = input('type');
        $data['value'] = input('value');
        $id = input('id');
        $app = AgentAppModel::get($id);
        $user = session('user');
        $app->confirm_user = $user['user_id'];

        $app->comments .= '<p>管理员回复:</p>'.$data['value'];
        if ($type == 'ok') {
            $app->application_status = '已通过';
            UserModel::get($app->user->user_id)->mails()->save(config('msg.send_agent_ok'));
        } else {
            $app->application_status = '未通过';
            $para = config('msg.send_agent_error');
            $para['content'] = strtr($para['content'], ['%comment%' => $app->comments]);
            UserModel::get($app->user->user_id)->mails()->save($para);
        }
        $app->save();

        return success('操作成功');
    }

    /**
     * 区域代理列表.
     */
    public function showList()
    {
        if (session('user')->user_type == 'user' or session('user')->user_type == 'agent') {
            return error('没有权限');
        }
        $where = array();
        $where['application_status'] = ['neq', 2];
        if ($keyword = input('keyword')) {
            $user = UserModel::where('user_name|user_uniid', 'like', '%'.$keyword.'%')->field('user_id')->select();
            foreach ($user as $u) {
                $user_ids[] = $u['user_id'];
            }
            if ($user_ids) {
                $where['user_id'] = ['in', $user_ids];
            } else {
                $where['location'] = ['like', '%'.$keyword.'%'];
            }
        }
        if ($type = input('type')) {
            switch ($type) {

                case 'all':
                    break;

                case 'ok':
                    $where['application_status'] = 1;
                    break;

                case 'error':

                    $where['application_status'] = 0;
                    break;

                default:
                    break;
            }
        } else {
            $type = 'all';
        }

        $list = AgentAppModel::where($where)->order('create_time DESC')->paginate(getPageSize());
//        echo AgentAppModel::getLastSql();
//        exit;
        table_empty_list($list);

        return view('showlist', ['list' => $list, 'keyword' => $keyword, 'type' => $type]);
    }
    public function create_ticket()
    {
        if (session('user')->user_type == 'user') {
            return error('没有权限');
        }
        if (IS_POST) {

          //  try {
                $usr = UserModel::get(session('user_id'));
            if ($usr->user_type == 'user') {
                return error('非法请求');
            }
            $data = input('post.');
            $data['times'] = intval($data['times']);
            if ($data['times'] < 1) {
                return error('次数不正确');
            }
            $least_value = SysconfigModel::where('en', 'business_lowTicket')->find()->value;
            if ($data['cash_value'] < $least_value) {
                return error('排队金额最少为'.$least_value);
            }
            $target_user = UserModel::where('user_uniid', $data['user_uniid'])->find();
            if (!$target_user->user_id) {
                return error('没有这个用户');
            }
            if ($target_user->user_status != '已认证') {
                return error('该用户未认证，不能排队');
            }
            if ($data['cash_value'] < 0) {
                return error('排队金额不正确');
            }
            $count = $target_user->tickets()->count();

            if ($usr->user_type != 'superuser') {
                $cash = $usr->line_cash;
                if ($data['cash_value'] * $data['times'] > $cash) {
                    return error('余额不足');
                }
                $usr->consumes()->save(['cash_type' => '报单币', 'cash_value' => $data['cash_value'] * $data['times'], 'cash_flow_comments' => '为用户'.$target_user->user_uniid.'添加排单']);
            }

            for ($i = 0; $i < $data['times']; ++$i) {
                $result = $usr->owned_line->members()->save([
                    'value' => $data['cash_value'],
                    'user_id' => $target_user->user_id,
                  ]);
                $para = config('msg.send_ticket_recived');
                $para['content'] = strtr($para['content'], ['%linename%' => $usr->owned_line->line_name, '%ticketid%' => LineTicketModel::get($result)->ticket_id]);
                $target_user->mails()->save($para);

                if ($count == 0) {
                    //发推荐奖
                      if ($target_user->account_type == '普通会员') {
                          $value = SysconfigModel::where('en', 'business_recommendPrice')->find()->value;
                      } else {
                          $value = SysconfigModel::where('en', 'business_recommendPriceVip')->find()->value;
                      }

                    if ($target_user->parent_user) {
                        if ($target_user->parent_user->user_type == 'user' and $target_user->parent_user->account_type == UserModel::$account_type_category[0]) {
                        } else {
                            $target_user->parent_user->awards()->save(['award_type' => '推荐奖', 'cash_value' => $value, 'cash_flow_comments' => '成功推荐会员编号 '.$target_user->user_uniid.' 并进行消费。']);
                            $para = config('msg.send_award_recommend');
                            $para['content'] = strtr($para['content'], ['%uniid%' => $target_user->user_uniid, '%username%' => $target_user->user_name, '%value%' => $value]);
                            $target_user->parent_user->mails()->save($para);
                        }
                    }
                }

                //发财富币奖
                $first_percent = SysconfigModel::where('en', 'business_firstPercent')->find()->value;
                $second_percent = SysconfigModel::where('en', 'business_secondPercent')->find()->value;
                $award_agent = clone $target_user;
                while ($award_agent->user_type == 'user' and $award_agent->parent_user) {
                    $award_agent = $award_agent->parent_user;
                }
                if ($award_agent->user_type == 'agent') {
                    $award_agent->awards()->save(['award_type' => '财富币奖', 'cash_value' => $data['cash_value'] * $first_percent * 0.01, 'cash_flow_comments' => '推荐会员编号 '.$target_user->user_uniid.' 进行消费而获得返利。']);

                    if ($award_agent->parent_user) {
						if(($award_agent->parent_user->user_type == 'user' and $award_agent->parent_user->account_type==UserModel::$account_type_category[1]) or $award_agent->parent_user->user_type == 'agent')
						{
							$award_agent->parent_user->awards()->save(['award_type' => '财富币奖', 'cash_value' => $data['cash_value'] * $second_percent * 0.01, 'cash_flow_comments' => '您的下级 '.$target_user->parent_user->user_uniid.' 所推荐会员编号 '.$target_user->user_uniid.' 进行消费而获得返利。']);
						}	
                    }
                }

              //判断队列出局
                  $step = SysconfigModel::where('en', 'business_line_rule')->find()->value;
                $line = LineModel::get($usr->owned_line->line_id);
                $count = $line->members()->where('ticket_status', '<>', 2)->count();
                if ($step <= $count - $line->outed_range) {
                    $ticket = $line->members()->where('ticket_status', '<>', 2)->where('rank', $line->outed_num + 1)->find();
                    $ticket->save(['ticket_status' => '已出局']);
                    $value = $ticket->value * SysconfigModel::where('en', 'business_out_percent')->find()->value / 100;
                    $award = $ticket->user->awards()->save(['award_type' => '出局奖', 'cash_value' => $value, 'cash_flow_comments' => '排劵号 '.$ticket->ticket_id.' 出局奖励。']);
                    $cash = CashFlowModel::get($award);
                    $cash->cash_flow_status = '已完成';
                    $cash->save();
                    $para = config('msg.send_award_outed');
                    $para['content'] = strtr($para['content'], ['%ticketid%' => $ticket->ticket_id, '%value%' => $value]);
                    $ticket->user->mails()->save($para);
                    if ($ticket->user->vaild_card) {
                        $ticket->user->encashments()->save([
                          'cash_value' => $value,
                          'card_id' => $ticket->user->vaild_card->card_id,
                        ]);
                    }
                }
            }

            return success('提交成功');
          //  } catch (\Exception $e) {
            //    return error($e->getMessage());
          //  }
        }

        return error('非法请求');
    }
    /**
     * 一线公排.
     */
    public function lineupList($line_id = 0, $keyword = '')
    {
        $usr = UserModel::get(session('user_id'));
        if ($usr->user_type == 'user') {
            $lines = $usr->tickets()->distinct(true)->column('line_id');
            if ($lines) {
                $linelist = LineModel::all($lines);
            }
            $this->assign('linelist', $linelist);
			if($lines)
			{
				$list = LineTicketModel::where('ticket_status', '<>', 2)->where('line_id','in',$lines);
			}else{
				$list = LineTicketModel::where(false);
			}
        } elseif ($usr->user_type == 'agent') {
            $myline = $usr->owned_line->line_id;
            $list = LineTicketModel::where('ticket_status', '<>', 2)->where('line_id', $myline);
            $city = explode(self::$ZWSP, $usr->owned_line->line_name);
            if (count($city) > 1) {
                $city_name = $city[0].self::$ZWSP.$city[1];
                $linelist = LineModel::has('members')->where('line_name', 'like', $city_name.'%')->select();
            }
            $this->assign('linelist', $linelist);
        } else {
            $list = LineTicketModel::where('ticket_status', '<>', 2);
            $linelist = LineModel::has('members')->select();
            $this->assign('linelist', $linelist);
        }
        if ($line_id != 0) {
            if ($usr->user_type == 'agent') {
                $line = LineModel::get($line_id);
                if (!$line or $cityname and strpos($line->line_name->city_name, $city_name) == 0) {
                    return error('非法操作');
                }
                $list = LineTicketModel::where('ticket_status', '<>', 2)->where('line_id', $line_id);
            } else {
                $list = $list->where('line_id', $line_id);
            }
        }
        if (!empty($keyword)) {
            $user = UserModel::where('user_name|user_uniid', 'like', '%'.$keyword.'%')->field('user_id')->select();
            foreach ($user as $u) {
                $user_ids[] = $u['user_id'];
            }
            if ($user_ids) {
                $where['user_id'] = ['in', $user_ids];
            }
            $list = $list->where($where);
        }

        $countall = clone $list;
        $countall = $countall->count();
        $countout = clone $list;
        $countout = $countout->where('ticket_status', 1)->count();
        $list = $list->paginate(getPageSize());
        table_empty_list($list);

        $this->assign('list', $list);
        $this->assign('user', $usr);
        $this->assign('line_id', $line_id);
        $this->assign('keyword', $keyword);
        $this->assign('countall', $countall);
        $this->assign('countout', $countout);

        return $this->fetch();
    }
}
